package com.rede.didiok.rank.service.impl;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rede.didiok.common.enums.AttrSearchTypeEnum;
import com.rede.didiok.common.enums.AttrValueTypeEnum;
import com.rede.didiok.common.utils.ListUtils;
import com.rede.didiok.common.utils.PageUtils;
import com.rede.didiok.common.utils.Query;
import com.rede.didiok.rank.dao.AttrAttrgroupRelationDao;
import com.rede.didiok.rank.dao.AttrDao;
import com.rede.didiok.rank.dao.AttrGroupDao;
import com.rede.didiok.rank.dao.RankCategoryDao;
import com.rede.didiok.rank.entity.*;
import com.rede.didiok.rank.service.AttrService;
import com.rede.didiok.rank.service.RankCategoryService;
import com.rede.didiok.rank.vo.AttrGroupRelationVo;
import com.rede.didiok.rank.vo.AttrRespVo;
import com.rede.didiok.rank.vo.AttrVo;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    RankCategoryDao rankCategoryDao;

    @Resource
    RankCategoryService rankCategoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrVo attr) {
        // 1. 保存基础数据
        AttrEntity attrEntity = new AttrEntity();
        // 当属性支持多选时就不支持检索
        if (AttrValueTypeEnum.MULTI.getCode().equals(attrEntity.getValueType())) {
            attrEntity.setSearchType(AttrSearchTypeEnum.NOT_SEARCH.getCode());
        }
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        // 2. 维护关联关系 属性与属性分组
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrUid(attrEntity.getUid());
        attrAttrgroupRelationEntity.setGroupUid(attr.getGroupUid());
        attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
    }

    /**
     * 根据分类查询榜单的属性
     *
     * @param params
     * @param catId
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();

        if (catId != 0L) {
            queryWrapper.eq("cat_id", catId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            //attr_id  attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //1、设置分类和分组的名字
            if (StringUtils.isEmpty(attrRespVo.getGroupName())) {
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getUid()));
                if (attrId != null && attrId.getGroupUid() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getGroupUid());
                    attrRespVo.setGroupName(attrGroupEntity.getGroupName());
                }
            }

            if (StringUtils.isEmpty(attrRespVo.getCatName())) {
                RankCategoryEntity rankCategoryEntity = rankCategoryDao.selectById(attrEntity.getCatUid());
                if (rankCategoryEntity != null) {
                    attrRespVo.setCatName(rankCategoryEntity.getCatName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);

        //1、设置分组信息
        if (StringUtils.isEmpty(respVo.getGroupUid())) {
            AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            // 可能属性与属性分组没有关联关系,所以需要非空判断
            if (attrgroupRelation != null) {
                respVo.setGroupUid(attrgroupRelation.getGroupUid());
                if (StringUtils.isEmpty(respVo.getGroupName())) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getGroupUid());
                    if (attrGroupEntity != null) {
                        respVo.setGroupName(attrGroupEntity.getGroupName());
                    }
                }
            }
        }


        //2、设置分类信息
        String catUid = attrEntity.getCatUid();
        if (!StringUtils.isEmpty(catUid)) {
            String[] catelogPath = rankCategoryService.findCatelogPath(catUid);
            respVo.setCatelogPath(catelogPath);

            RankCategoryEntity rankCategoryEntity = rankCategoryDao.selectById(catUid);
            if (rankCategoryEntity != null) {
                respVo.setCatName(rankCategoryEntity.getCatName());
            }
        }

        return respVo;
    }

    /**
     * 修改属性、属性和属性分组关联关系
     *
     * @param attr
     */
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 修改属性
        this.updateById(attrEntity);
        // 修改属性和属性分组关系
        if (attr.getGroupUid() != null) {
            //1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setGroupUid(attr.getGroupUid());
            relationEntity.setGroupUid(attr.getGroupUid());

            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getUid()));
            if (count > 0) {
                // 存在就修改
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getUid()));

            } else {
                // 不存在就新增
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id查询所有关联的基本属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("group_id", attrGroupId));
        List<String> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrUid();
        }).collect(Collectors.toList());

        if (ListUtils.isEmpty(attrIds)) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 删除属性分组与属性关系
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //relationDao.delete(new QueryWrapper<>().eq("attr_id",1L).eq("attr_group_id",1L));
        //
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     *
     * @param params
     * @param groupUid
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long groupUid) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupUid);
        String catUid = attrGroupEntity.getCatUid();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、获取同一分类下的所有分组（包括当前分组）
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("cat_uid", catUid));
        List<String> collect = group.stream().map(item -> {
            return item.getUid();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("group_uid", collect));
        List<String> attrIds = relationEntities.stream().map(item -> {
            return item.getAttrUid();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        // 当前分类下所有的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("cat_uid", catUid);
        if (attrIds != null && attrIds.size() > 0) {
            // 去除已经关联的属性
            wrapper.notIn("attr_uid", attrIds);
        }
        // 拼接条件查询
        String key = (String) params.get("key");
        if (!org.springframework.util.StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_uid", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    /**
     * 在指定的所有属性集合里面，挑出检索属性
     *
     * @param attrIds
     * @return
     */
    @Override
    public List<String> selectSearchAttrIds(List<String> attrIds) {
        /**
         * SELECT attr_id FROM `rank_attr` WHERE attr_id IN(?) AND search_type = 1
         */
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}